import path from "path";
import downloadGitRepo from "download-git-repo";
import util from "util";
import ora from "ora";
import inquirer from "inquirer";
import { getRepoList, getTagList } from "./http.js";
import { githubConfig } from "../config/repoConfig.js";

async function wrapLoading(fn, message, ...args) {
  const spinner = ora(message);
  spinner.start();

  try {
    const result = await fn(...args);
    spinner.succeed();
    return result;
  } catch (error) {
    spinner.fail("fetch failed");
  }
}

class Generator {
  constructor(name, targetDir) {
    this.name = name; // 目录名
    this.targetDir = targetDir; // 创建位置
    this.downloadGitRepo = util.promisify(downloadGitRepo);
  }

  // 获取模版
  async getRepo() {
    // 1、远程拉取模版数据
    const repoList = await wrapLoading(getRepoList, "searching repos");

    // 2、过滤出我们需要的模版(这块可能需要结合用户传入的参数的)
    const repos = repoList.map((item) => {
      // 实际情况比较复杂，一般都会进行针对性的单项操作
      // 如果不这么做，直接使用filter即可.比如模版类仓库名中一般会含有template字段，按照此关键字段做一下过滤
      return item.name;
    });
    // 3、选一个喜欢的模版
    const { repo } = await inquirer.prompt({
      name: "repo",
      type: "list",
      choices: repos,
      message: "请选择一个模版进行创建",
    });
    return repo;
  }

  // 获取版本
  async getTag(repo) {
    // 拉取对应的tag列表
    const tags = wrapLoading(getTagList, "waiting tags downloading", repo);

    if (!tags) return;

    // 过滤tag名称
    const tagList = tags.map((item) => item.name);

    return tagList[0];
  }

  // 模版下载
  async download(repo) {
    const requestUrl = `${githubConfig.owner}/${repo}`;
    const targetPath = path.resolve(process.cwd(), this.targetDir);
    this.downloadGitRepo(requestUrl, targetPath, (err) => {
      if (err) {
        console.log("模版下载报错：", err);
        return;
      }
    });
  }

  // 核心创建逻辑
  async create() {
    const repo = await this.getRepo();
    this.download(repo);
  }
}

export default Generator;
